import { defineStore } from "pinia";
import { setItem } from "@/utils/storage";
import { collectApi, fetchSearchList, fetchClientPhone } from "@/api";
export const personStore = defineStore("person", {
  unistorage: true, // 是否持久化到内存
  state: () => {
    return {
      userIds: {}, // user_id、 s_user_id
      searchParams: {}, //
      shareParams: {},
      personListRes: {},
      fullPhone: "", // 完整手机号
    };
  },
  actions: {
    updatePersonId(ids) {
      this.userIds = ids;
      setItem("userIds", ids);
    },

    updateSearchParams(data) {
      this.searchParams = data;
    },

    updateFullPhone(data) {
      this.fullPhone = data;
    },

    // 收藏 、 取消收藏
    updateCollect(params) {
      return new Promise(async (resolve, reject) => {
        try {
          const { s_user_id, collect } = params;
          if (collect) {
            uni.showModal({
              content: "将此人从收藏联系人中删除？",
              confirmText: "删除此人",
              confirmColor: "#576B95",
              success: (res) => {
                if (res.confirm) {
                  collectApi({ s_user_id })
                    .then((res) => {
                      resolve(res.msg);
                    })
                    .catch((err) => {
                      reject(err);
                    });
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              },
            });
          } else {
            collectApi({ s_user_id })
              .then((res) => {
                resolve(res.msg);
              })
              .catch((err) => {
                reject(err);
              });
          }
        } catch (error) {
          reject(error);
        }
      });
    },

    // 搜索结果页面
    getPersonList(page) {
      return new Promise((resolve, reject) => {
        const newParams = {
          where: this.searchParams,
          limit: 4,
          page,
        };
        fetchSearchList(newParams)
          .then((res) => {
            let { data } = res;
            if (data.list?.length) {
              data.list = data.list?.map((v) => {
                v.year = String(v.year).slice(-2);
                v.imgs = v.img || [];
                return v;
              });
            } else {
              data.list = [];
            }

            this.personListRes = data;
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    // 获取完整电话号码
    getPhone(s_user_id) {
      return new Promise((resolve, reject) => {
        fetchClientPhone({ s_user_id })
          .then((res) => {
            if (res.data) {
              this.fullPhone = res.data.length ? res.data : "";
              resolve(this.fullPhone);
            } else {
              resolve("");
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
});
